
import { getPreOrderMsgFun, getInfo, createOrder } from '../../api/order'
import { getTicketDetail, getShopList } from '../../api/good'
import {getGoodsAndShopJoinPayChannels} from "@src/api/mall/store";
import router from "@src/router";
import mall from "@src/store/mall";
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import base from "@src/store/base";
import mallPayBehavior from "@mall/pages/submit-order/mallPayBehavior";
Component({
  behaviors: [storeBindingsBehavior, mallPayBehavior],
  storeBindings: [{
    store: mall,
    fields: ['curLocation'],
    actions: ['initLocation','goodsAndShopJoinPay']
  }, {
    store: base,
    fields: ['themeColor', 'themeTitleColor']
  },],
  /**
   * 页面的初始数据
   */
  data: {
    //店铺信息
    storeMsgObj: null,
    //商品信息
    itemsObj: null,
    //服务信息
    serviceList: null,
    //订单信息
    orderPayInfo: null,

    hiddenPay: true,
    //会员余额
    personBalance: null,
    //支付方式
    payType: null,
    //预下单编号
    preNo: null,
    //订单号
    orderNo: null,
    supportWX: false,
    supportBALANCE: false,
    ticketlist: [],
    hiddenticket: true,
    ticketObj: {},
    preOrder:null

  },
  methods: {

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      this.$pay = this.selectComponent("#pay");
      this.initLocation();
      const self = this;
      console.log('options--', options)
      let preNo = options.preNo;
      let storeNo = options.storeNo;
      this.setData({
        preNo: preNo,
        storeNo:storeNo
      })
      getPreOrderMsgFun(preNo).then(res => {
        console.log("预下单西", res)
        if (res.code == 0) {
          if (res.data.errorCode) {
            wx.showToast({
              title: res.data.errorMsg,
              icon: 'none',
              duration: 6000
            })
            setTimeout(() => {
              wx.navigateBack();
            }, 2000)

            return;
          }

          let arr1 = res.data.store.serviceList ? res.data.store.serviceList : [];
          let arr2 = res.data.items[0].serviceList ? res.data.items[0].serviceList : [];
          let arrTemp = arr1.concat(arr2)
          // 存在活动那么就是代表团长
          if(res?.data?.groupInfo?.isLeader && res?.data?.orderPayInfo?.activityDiscounts?.length>0){
            // res.data.items[0].price -=   res?.data?.orderPayInfo?.activityDiscounts[0].discountFee
          }
          self.setData({
            storeMsgObj: res.data.store,
            itemsObj: res.data.items[0],
            serviceList: arrTemp,
            orderPayInfo: res.data.orderPayInfo,
            preOrder:res.data

          })

          console.log('serviceList', this.data.serviceList)

          //判断支付方式
          if (this.data.orderPayInfo.payChannels.includes('BALANCE')) {
            this.setData({
              supportBALANCE: true
            })
          }
          if (this.data.orderPayInfo.payChannels.includes('WX')) {
            this.setData({
              supportWX: true
            })
          }



          // if ((self.data.orderPayInfo.totalFee) / 100 > personBalance) {
          //   this.setData({
          //     payType: 1,
          //   })
          // } else {
          //   this.setData({
          //     payType: 0,
          //   })
          // })

          console.log('父组件里的', this.data.orderPayInfo.payChannels)

          this.assemblyTicketData()


        }
      })

      getInfo().then(res => {
        console.log('会员余额res', res)
      })


    },

    async gopay() {
      const payCross = await this.goodsAndShopJoinPay(this.data.orderPayInfo.totalFee,[this.data.itemsObj],this.data.storeMsgObj.storeId)
      console.log('payCross----',payCross)
      if(!payCross){
       return
      }
      const self = this;
      let createForm = {};
      let item = []
      //获取会员余额
      getInfo().then(res => {

        if (res.code == 0) {
          let personBalance = (res.data.balance + res.data.giftBalance - res.data.lockedBalance - res.data.lockedGiftBalance) / 100;
          this.setData({
            personBalance: personBalance,
          })
        } else if (res.code == 50404) {
          let personBalance = 0
          this.setData({
            personBalance: personBalance,
          })
        }



        if (this.data.supportWX) {
          this.setData({
            payType: 1,
          })
        }
        console.log("(self.data.orderPayInfo.totalFee) / 100", (self.data.orderPayInfo.totalFee) / 100);
        console.log("personBalance", self.data.personBalance)
        if ((self.data.orderPayInfo.totalFee) / 100 < self.data.personBalance || (self.data.orderPayInfo.totalFee) / 100 == self.data.personBalance) {
          if (this.data.supportBALANCE) {
            this.setData({
              payType: 0,
            })
          }

        }



        console.log("父组件中payType", this.data.payType)
      })

      // 获取商品购买的支付方式
      let buyChannels = ''
      let idArr = []
      let goodsIdList = [this.data.itemsObj]
      goodsIdList.forEach(el => {
        idArr.push(el.goodsId)
      })
      let parmData = {
        goodsIdList:idArr,
        storeId:this.data.storeMsgObj.storeId,
      }
      getGoodsAndShopJoinPayChannels(parmData).then(res => {
        buyChannels = res.data
      })

      //组装参数对象
      item.push(this.data.itemsObj)
      createForm.items = item;
      createForm.source = {
        preNo: this.data.preNo,
        source: 0
      }
      createForm.storeId = this.data.storeMsgObj.storeId
      createForm.type = 'VIRTUAL'
      createForm.subType = this.data.preOrder.subType
      createForm.storeNo = this.data.storeNo
      if (this.data.preOrder.orderFrom && this.data.preOrder.orderFrom.activitySceneStr) {
        createForm.source.activitySceneStr = this.data.preOrder.orderFrom.activitySceneStr
        createForm.source.activityNo = this.data.preOrder.orderFrom.activityNo
        createForm.activityType = this.data.preOrder.subType || null
        createForm.items.forEach((item, index) => {
          item.activitySceneStr = this.data.preOrder.orderFrom.activitySceneStr
        })
      }
      createOrder(createForm).then(res => {
        wx.hideLoading()
        if (res.code !== 0) {
          this.selectComponent("#toast").show({icon: "error", txt: res.msg, type: 'info', time: 2000});
          return;
        }
        let orderNo = res.data.orderNo;
        let payFee = res.data.payFee;
        let payChannels = [];
        // 店铺和商品的支付方式判断
        if (this.data.orderPayInfo.payChannels.indexOf("WX") !== -1 && buyChannels.supplyWxPay) {
          payChannels.push("wx")
        }
        if (this.data.orderPayInfo.payChannels.indexOf("BALANCE") !== -1 && buyChannels.supplyBalance) {
          payChannels.push("balance")
        }
        let data = {
          orderNo: orderNo,
          payFee: payFee,
          payChannels: payChannels,
          hasDiscount: false
        }
        this.toMallPay(data).then(res => {
          console.info("成功", res)
          this.selectComponent("#toast").show({icon: "", txt: "支付成功, 跳转中...", type: 'info', time: 2000});
          setTimeout(() => {
            router.redirectTo({name: 'mall/order-detail', params: {orderNo: orderNo}});
          }, 300)
        }).catch(res => {
          if (res && res.code === "cancel") {
            router.redirectTo({name: 'mall/order-detail', params: {orderNo: orderNo}});
            return;
          }
          // 支付失败
          this.selectComponent("#toast").show({icon: "error", txt: res.msg, type: 'info', time: 2000});
          setTimeout(() => {
            router.redirectTo({name: 'mall/order-detail', params: {orderNo: orderNo}});
          }, 1500)
        })
      }).catch((e) => {
        console.error(e)
        wx.hideLoading()
        this.selectComponent("#toast").show({icon: "error", txt: "请求异常, 下单失败", type: 'info', time: 2000});
      })
    },
    //组装items 券数据
    assemblyTicketData() {
      let itemsObj = this.data.itemsObj
      itemsObj.items.forEach(item => {
        item.tickethidden = true
      })

      this.setData({
        itemsObj: itemsObj
      })



    },
    //显示券详情
    handleShowCoupon(e) {
      let item = e.currentTarget.dataset.item
      if (item.itemType === 'COUPON') {
        this.selectComponent("#couponDetail").open(item);
      } else  {
        this.selectComponent("#couponDetailNew").open(item);
      }
    },
    //跳转到订单详情页
    setHiddentrueFunc() {
      const self = this;
      router.redirectTo({ name: "mall/order-detail", params: { orderNo: self.data.orderNo } })
    },
    setModeActive(e) {
      this.setData({
        acticeDistribution: e.currentTarget.dataset.index
      })
    },
    //监听滚动的位置
    mintorScroll(e) {


      if (e.detail.scrollTop > 80) {
        this.setData({
          isShowAddressTitle: false
        })
      } else {
        this.setData({
          isShowAddressTitle: true
        })
      }
    },
  }
})
